import copy
import os
import sys
import json
import time
import traceback
import threading
import numpy as np
from loguru import logger
from datetime import datetime, timedelta
from monitor import Monitor, Congestion
from util import get_latest_folder, get_pass_time


dir = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(dir, "Log", "logs")
if not os.path.exists(log_dir):
    os.makedirs(log_dir, exist_ok=True)
# 自定义日志格式
logger.remove()  # 移除默认的日志处理器
logger.add(sink=sys.stdout,
           format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {function}:{line} - {message}",
           level="INFO")
logger.add(
    sink=os.path.join(log_dir, "event_{time:YYYY-MM-DD}.log"),  # 日志文件名带日期
    format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {function}:{line} - {message}",
    rotation="00:00",           # 每天午夜轮转（与大小轮转二选一）
    retention="360 days",       # 保留最近360天的日志
    encoding="utf-8",           # 避免中文乱码
    level="INFO",               # 文件日志级别
)


def setup_thread_logger(thread_id):
    """
    配置子线程的日志记录器。
    :param thread_id: 子线程ID，用于生成唯一的日志文件名。
    """
    thread_log_file = os.path.join(log_dir, f"thread_{thread_id}.log")
    # 添加一个新的sink，只允许当前线程的日志写入
    logger.add(
        thread_log_file,
        level="INFO",
        backtrace=False,
        diagnose=False,
        encoding="utf-8",
        filter=lambda record: record["extra"].get("thread") == thread_id
    )
    return logger.bind(thread=thread_id)


def dynamic_mad_filter(data, n_mad=3.0, base_factor=2.0, sensitivity=0.1):
    """
    动态MAD异常值过滤

    参数:
        data: 输入数据列表/数组
        n_mad: 标准MAD乘数(默认3.0)
        base_factor: 最小MAD乘数(默认2.0)
        sensitivity: 数据量敏感系数(默认0.1)

    返回:
        过滤后的数据平均值
    """
    if not data:
        return []

    data = np.array(data)
    median = np.median(data)
    mad = 1.4826 * np.median(np.abs(data - median))

    # 动态调整因子
    n = len(data)
    dynamic_factor = max(base_factor, n_mad - sensitivity * n)
    upper_limit = median + dynamic_factor * mad
    lower_limit = median - dynamic_factor * mad

    # 过滤异常值
    filtered = data[(data >= lower_limit) & (data <= upper_limit)]
    # print("Filtered speeds:", filtered)

    # 如果没有数据通过过滤，返回中位数
    return filtered


class ProcessEvent:
    def __init__(self, config_data, define):
        self.config_data = config_data
        # self.format_str = self.config_data["format_str"]
        self.gantry_info = self.config_data["gantry_info"]
        self.define = define
        # 时间窗口
        # self.window_length = timedelta(minutes=float(self.gantry_info['time_interval']))
        self.window_length = None
        # 移动时间
        self.time_move = timedelta(minutes=float(self.gantry_info['time_move']))
        # self.route_list = self.config_data["route"]
        # 门架数据
        self.gantry_data = {}
        # 实时时间
        self.current_simulated_time = None
        self.load_time = None
        self.diff_time = None
        # 时间窗口
        self.start_time = None
        self.end_time = None
        # 接收的最后一帧数据
        self.last_car = None
        # 事件分析
        self.monitor = Monitor(self.config_data["threshold"])
        # 拥堵分析
        self.congestion = Congestion(self.define, self.config_data)
        # 线程管理
        self.thread_flag = True
        # 各车型期望通行时间表
        self.type_pass_time = {}
        # 各车型通行时间表
        self.type_pass_time_ture = {}
        # 保存事故数据地址
        self.save_json_path = None
        # 是否保存过程数据
        self.SAVE = True
        # 结束标志位
        self.flag = None
        self.current_time_str = None
        # 子线程日志记录器
        # self.thread_logger = setup_thread_logger(self.gantry_info["info"])

    def init(self):
        # current_up_list、current_down_list 存储当前时间区间内上下游车辆数量，保存为时间列表
        # up_data_dict、down_data_dict   存储上下游门架数据，保存到以车牌为键的字典
        # detention_dict    滞留车辆字典，暂时未用
        # interval_dict       存储当前时间区间内车辆信息
        # up_vlp_time_dict、down_vlp_time_dict    计算通行率时长字典
        self.gantry_data = {
            "current_up_list": [],
            "current_down_list": [],
            "up_data_dict": {},
            "down_data_dict": {},
            "detention_dict": {},
            "interval_dict": {},
            "up_vlp_time_dict": {},
            "down_vlp_time_dict": {},
            "in_num": 0,
            "out_num": 0
        }
        # 按指定速度计算合适的区间通行时间
        self.type_pass_time = get_pass_time(self.gantry_info["dist"])
        # 设置时间粒度
        # self.window_length = timedelta(minutes=float(self.type_pass_time["1"] * 0.5))
        self.window_length = timedelta(minutes=float(self.config_data["gantry_info"]["time_interval"]))

    def save_json(self, time_str):
        json_dir = os.path.join(self.config_data["save_json_path"], time_str)
        if not os.path.exists(json_dir):
            os.makedirs(json_dir, exist_ok=True)
        return os.path.join(json_dir, f"{self.gantry_info['info']}.jsonl")

    def add_message(self, q):
        '''
        更新新的门架数据
        '''
        while not q.empty():
            message = q.get(timeout=0.1)
            # print("收到消息:", message)
            current_time0 = message[self.define["TIME"]]
            # self.current_simulated_time = datetime.strptime(current_time0, self.format_str)
            self.current_simulated_time = datetime.fromtimestamp((current_time0 / 1000))
            # 初始化时间
            if self.diff_time is None:
                self.load_time = datetime.now()
                self.diff_time = self.current_simulated_time - self.load_time
            if self.start_time is None:
                # self.start_time = datetime.strptime(current_time0, self.format_str)
                self.start_time = self.current_simulated_time
                self.end_time = self.start_time + self.window_length
            # 添加新的门架数据
            gantry_id = message[self.define["GANTRY"]]
            if gantry_id in self.gantry_info["up_gantry_id"]:
                # current_time = datetime.strptime(message[self.define["TIME"]], self.format_str)
                current_time = datetime.fromtimestamp((current_time0 / 1000))
                vlp = message[self.define["PLATE"]]
                # 20250414 gj 去掉去重操作，融合数据已经去重
                # if vlp in self.gantry_data["up_data_dict"].keys():
                #     # if current_time - self.gantry_data["up_data_dict"][vlp][self.define["TIME"]] <= timedelta(minutes=30):
                #     continue
                # 添加新的上游门架过车的时间信息
                self.gantry_data["current_up_list"].append(current_time)
                # 添加新的上游门架过车信息
                self.gantry_data["up_data_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                         self.define["TIME"]: current_time}
                self.gantry_data["interval_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                          self.define["TIME"]: current_time}
                # 更新上游车辆数量
                self.gantry_data["in_num"] += 1
            elif gantry_id in self.gantry_info["down_gantry_id"]:
                # current_time = datetime.strptime(message[self.define["TIME"]], self.format_str)
                current_time = datetime.fromtimestamp((current_time0 / 1000))
                vlp = message[self.define["PLATE"]]
                if vlp in self.gantry_data["down_data_dict"].keys():
                    continue
                # 添加新的下游门架过车的时间信息
                self.gantry_data["current_down_list"].append(current_time)
                # 添加新的下游门架过车信息
                self.gantry_data["down_data_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                           self.define["TIME"]: current_time}
                self.gantry_data["down_vlp_time_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                               self.define["TIME"]: current_time}
                # 更新下游车辆数量
                self.gantry_data["out_num"] += 1
                # 删除interval_dict中车辆经过下游的车辆信息
                if vlp in self.gantry_data["interval_dict"].keys():
                    del self.gantry_data["interval_dict"][vlp]

    def expire_clear(self, start_time, end_time, flag=True):
        # 清除过期数据(一小时前未匹配上的上游门架数据)
        # save_time = self.gantry_info["car_pass_time"] + self.config_data["time_move"]
        save_time = 60
        max_pass_time = 0
        if not flag:
            max_pass_time = self.type_pass_time["1"]
        else:
            for i in self.type_pass_time.keys():
                if self.type_pass_time[i] > max_pass_time:
                    max_pass_time = self.type_pass_time[i]
        pass_time = max_pass_time + self.gantry_info["time_move"]
        min_pass_time = max_pass_time * 0.5
        # 清除时间过期数据，只保留当前时间范围内的数据
        i = 0
        while i < len(self.gantry_data["current_up_list"]):
            if self.gantry_data["current_up_list"][i] < start_time:
                i += 1
            else:
                break
        self.gantry_data["current_up_list"] = self.gantry_data["current_up_list"][i:]
        j = 0
        while j < len(self.gantry_data["current_down_list"]):
            if self.gantry_data["current_down_list"][j] < start_time:
                j += 1
            else:
                break
        self.gantry_data["current_down_list"] = self.gantry_data["current_down_list"][j:]
        # print("过期数据:", i, j)
        # 删除过期save_time以上的上游门架数据
        del_up_vlp_list = []
        up_vlp_list = list(self.gantry_data["up_data_dict"].keys())
        for vlp in up_vlp_list:
            data_time = self.gantry_data["up_data_dict"][vlp][self.define["TIME"]]
            if data_time < end_time - timedelta(minutes=save_time):
                del_up_vlp_list.append(vlp)

        # 删除过期save_time以上的上游门架数据
        in_vlp_list = []
        self.gantry_data["up_vlp_time_dict"].clear()
        for vlp in up_vlp_list:
            data_time = self.gantry_data["up_data_dict"][vlp][self.define["TIME"]]
            if (start_time - timedelta(minutes=pass_time)) <= data_time < (
                    end_time - timedelta(minutes=min_pass_time + self.gantry_info["time_move"])):
                in_vlp_list.append(vlp)
        for vlp in in_vlp_list:
            up_vlp = self.gantry_data["up_data_dict"][vlp]
            self.gantry_data["up_vlp_time_dict"][vlp] = {self.define["TIME"]: up_vlp[self.define["TIME"]],
                                                         self.define["TYPE"]: up_vlp[self.define["TYPE"]]}
        for vlp in del_up_vlp_list:
            del self.gantry_data["up_data_dict"][vlp]

        # 删除当前时间区间以外的下游门架数据
        del_down_vlp_list = []
        down_vlp_list = list(self.gantry_data["down_data_dict"].keys())
        for vlp in down_vlp_list:
            data_time = self.gantry_data["down_data_dict"][vlp][self.define["TIME"]]
            if data_time < start_time:
                del_down_vlp_list.append(vlp)
        for vlp in del_down_vlp_list:
            del self.gantry_data["down_data_dict"][vlp]
        # 删除当前时间区间以外的下游门架数据
        out_vlp_list = []
        out_down_vlp_list = list(self.gantry_data["down_vlp_time_dict"].keys())
        for vlp in out_down_vlp_list:
            data_time = self.gantry_data["down_vlp_time_dict"][vlp][self.define["TIME"]]
            if data_time < start_time - timedelta(minutes=pass_time) + timedelta(minutes=min_pass_time):
                out_vlp_list.append(vlp)
        for vlp in out_vlp_list:
            del self.gantry_data["down_vlp_time_dict"][vlp]

        # 删除当前时间区间以外的滞留车辆数据
        interval_vlp_list = []
        out_interval_vlp_list = list(self.gantry_data["interval_dict"].keys())
        for vlp in out_interval_vlp_list:
            data_time = self.gantry_data["interval_dict"][vlp][self.define["TIME"]]
            if data_time < end_time - timedelta(hours=24):
                interval_vlp_list.append(vlp)
        for vlp in interval_vlp_list:
            del self.gantry_data["interval_dict"][vlp]

    def type_analysis(self, flag=True):
        type_speed_dict = {}
        type_pass_rate_dict = {}
        # last_type_pass_time_ture = self.type_pass_time_ture.copy()
        self.type_pass_time_ture = {}
        down_data_dict = self.gantry_data["down_data_dict"].copy()
        up_data_dict = self.gantry_data["up_data_dict"].copy()
        new_time = self.end_time - self.time_move - self.time_move
        # detention_dict = self.gantry_data["detention_dict"]
        # 根据下游过车信息匹配上游数据，计算车辆速度等信息
        vlp_list = list(down_data_dict.keys())
        for vlp in vlp_list:
            dist = None
            up_time = None
            down_time = down_data_dict[vlp][self.define["TIME"]]
            vehicle_type = down_data_dict[vlp][self.define["TYPE"]]
            # 查找上游门架对应车牌出现时间，计算平均速度
            if vlp in up_data_dict.keys():
                up_time = up_data_dict[vlp][self.define["TIME"]]
                dist = self.gantry_info["dist"]
            if dist is not None:
                dt = down_time - up_time
                dt_seconds = round(dt.total_seconds(), 2)
                dt_hours = dt_seconds / 3600
                speed = round((dist / dt_hours), 2) if dt_seconds > 0 else 0
                # 保存最新添加的车辆信息
                # if vlp not in last_type_pass_time_ture.keys():
                # logger.info(f"{self.gantry_info['info']} - {down_time}, {new_time}, {self.start_time}, {self.end_time}")
                if down_time >= new_time:
                    self.type_pass_time_ture[vlp] = {"timestamp": down_time,
                                                     "vlp": vlp,
                                                     "vtype": vehicle_type,
                                                     "duration": dt.total_seconds()}
                # 保存时间区间的各种速度信息
                if vehicle_type not in type_speed_dict.keys():
                    type_speed_dict[vehicle_type] = {}
                    type_speed_dict[vehicle_type]["speed_list"] = []
                    type_speed_dict[vehicle_type]["slow_level_list"] = []
                type_speed_dict[vehicle_type]["speed_list"].append(speed)
        # 计算平均速度，慢行数量等信息
        for vehicle_type in type_speed_dict.keys():
            speed_list = type_speed_dict[vehicle_type]["speed_list"].copy()
            final_speed_list = dynamic_mad_filter(speed_list)
            mean_speed = sum(final_speed_list) / len(final_speed_list) if len(final_speed_list) > 0 else 80
            type_speed_dict[vehicle_type]["mean_speed"] = round(mean_speed, 2)
            type_speed_dict[vehicle_type]["count"] = len(speed_list)
            # 判断是否慢行
            for i in range(len(speed_list)):
                slow_level = 0
                if speed_list[i] < 20:
                    slow_level = 4
                elif speed_list[i] < 30:
                    slow_level = 3
                elif speed_list[i] < 40:
                    slow_level = 2
                elif speed_list[i] < 60:
                    slow_level = 1
                type_speed_dict[vehicle_type]["slow_level_list"].append(slow_level)
            # 统计慢行小客车的数量
            slow_level_list = type_speed_dict[vehicle_type]["slow_level_list"].copy()
            level_0 = slow_level_list.count(0)
            level_1 = slow_level_list.count(1)
            level_2 = slow_level_list.count(2)
            level_3 = slow_level_list.count(3)
            level_4 = slow_level_list.count(4)
            type_speed_dict[vehicle_type]["slow_level_count"] = [level_0, level_1, level_2, level_3, level_4]
        # 计算通过率
        in_vlp_dict = self.gantry_data["up_vlp_time_dict"].copy()
        for vlp in in_vlp_dict.keys():
            in_time = in_vlp_dict[vlp][self.define["TIME"]]
            in_type = in_vlp_dict[vlp][self.define["TYPE"]]
            if not flag:
                if in_type != "1":
                    continue
            if in_type not in self.type_pass_time.keys():
                in_type = "0"
            pass_time_config = self.type_pass_time[in_type]
            want_time = in_time + timedelta(minutes=pass_time_config)
            if (self.start_time - self.time_move) <= want_time < (self.end_time - self.time_move):
                if in_type not in type_pass_rate_dict.keys():
                    type_pass_rate_dict[in_type] = {}
                    type_pass_rate_dict[in_type]["count"] = 0
                    type_pass_rate_dict[in_type]["pass"] = 0
                    type_pass_rate_dict[in_type]["no_pass"] = 0
                type_pass_rate_dict[in_type]["count"] += 1
                if vlp in self.gantry_data["interval_dict"].keys():
                    type_pass_rate_dict[in_type]["no_pass"] += 1
        for in_type in type_pass_rate_dict.keys():
            type_pass_rate_dict[in_type]["pass"] = type_pass_rate_dict[in_type]["count"] - type_pass_rate_dict[in_type]["no_pass"]

            # want_time = in_time + timedelta(minutes=pass_time_config)
            # if(self.start_time - self.time_move) <= want_time < (self.end_time - self.time_move):
            #     if in_type not in type_pass_rate_dict.keys():
            #         type_pass_rate_dict[in_type] = {}
            #         type_pass_rate_dict[in_type]["count"] = 0
            #         type_pass_rate_dict[in_type]["pass"] = 0
            #     type_pass_rate_dict[in_type]["count"] += 1
            #     if vlp in self.gantry_data["down_vlp_time_dict"].keys():
            #         out_time = self.gantry_data["down_vlp_time_dict"][vlp][self.definene["TIME"]]
            #         pass_time = (out_time - in_time).total_seconds() / 60
            #         if pass_time <= pass_time_config:
            #             type_pass_rate_dict[in_type]["pass"] += 1
            # elif vlp in self.gantry_data["down_vlp_time_dict"].keys():
            #     if in_type not in type_pass_rate_dict.keys():
            #         type_pass_rate_dict[in_type] = {}
            #         type_pass_rate_dict[in_type]["count"] = 0
            #         type_pass_rate_dict[in_type]["pass"] = 0
            #     type_pass_rate_dict[in_type]["count"] += 1
            #     out_time = self.gantry_data["down_vlp_time_dict"][vlp][self.define["TIME"]]
            #     pass_time = (out_time - in_time).total_seconds() / 60
            #     if pass_time <= pass_time_config:
            #         type_pass_rate_dict[in_type]["pass"] += 1

        return type_speed_dict, type_pass_rate_dict

    def data_analysis(self):
        return_data = {}
        self.load_time = datetime.now()
        # 如果超过时间窗口，则移动时间窗口，并计算窗口内的各项数据
        if self.current_simulated_time is not None and self.diff_time is not None and (
                self.load_time + self.diff_time) >= self.end_time:
            a = time.time()
            # 计算当前时间窗口内的上下游车辆数量
            i = 0
            for t in self.gantry_data["current_up_list"]:
                if self.start_time <= t < self.end_time:
                    i += 1
            j = 0
            for t in self.gantry_data["current_down_list"]:
                if self.start_time <= t < self.end_time:
                    j += 1
            # 移动时间窗口
            self.start_time += self.time_move
            self.end_time += self.time_move
            # 将当前窗口内的数据计算并保存
            return_data["data"] = {"time": self.end_time - self.time_move,
                                   "up_flow_num": i,
                                   "down_flow_num": j,
                                   "in_num": self.gantry_data["in_num"],
                                   "out_num": self.gantry_data["out_num"],
                                   "interval_num": 0,
                                   "interval_dict": self.gantry_data["interval_dict"],
                                   "type_speed_dict": {},
                                   "type_pass_rate_dict": {}}
            self.gantry_data["in_num"] = 0
            self.gantry_data["out_num"] = 0
            return_data["info"] = self.gantry_info
            return_data["info"]["car_pass_time"] = self.type_pass_time["1"]
            return_data["info"]["time_interval"] = self.window_length
            return_data["info"]["time_move"] = self.time_move.total_seconds() / 60
            type_speed_dict, type_pass_rate_dict = self.type_analysis()
            return_data["data"]["type_speed_dict"] = type_speed_dict
            return_data["data"]["type_pass_rate_dict"] = type_pass_rate_dict
            return_data["data"]["type_pass_time_ture"] = self.type_pass_time_ture
            # 计算滞留车辆（由于门架卡口相机存在漏识别、误识别，会导致滞留车辆数量持续增高，带优化后使用该数据）
            for key in self.gantry_data["interval_dict"].keys():
                end_time = self.end_time - self.time_move
                if self.gantry_data["interval_dict"][key][self.define["TIME"]] <= end_time:
                    return_data["data"]["interval_num"] += 1

            # 清除过期数据(一小时前未匹配上的上游门架数据)
            self.expire_clear(self.start_time, self.end_time)

            # b = time.time()
            # logger.info("计算时间：%s" % (b - a))

        return return_data

    def get_flag(self, flag_q):
        '''
        监控线程是否需要结束
        '''
        while not self.flag:
            while not flag_q.empty():
                flag = flag_q.get(timeout=0.1)
                if flag:
                    self.flag = True

            time.sleep(0.1)

    def run(self, q, level, flag_q):
        # 启动监控线程
        threading.Thread(target=self.get_flag, args=(flag_q,)).start()
        # 初始化
        last_return_data = None
        now_time = datetime.now()
        # time_str = now_time.strftime("%Y%m%d")
        # json_dir = os.path.join(self.config_data["save_json_path"], time_str)
        # if not os.path.exists(json_dir):
        #     os.makedirs(json_dir, exist_ok=True)
        # self.current_time_str = time_str
        # filename = f"{self.gantry_info['info']}.json".lower()
        # self.save_json_path = os.path.join(json_dir, filename)
        # json_file = open(self.save_json_path, 'a', encoding='utf-8')

        while not self.flag:
            time.sleep(0.01)
            try:
                content = None
                con = None
                # 检查是否是新的一天，按天保存日志数据
                now_time = datetime.now()
                # time_str = now_time.strftime("%Y%m%d")
                # if time_str != self.current_time_str:
                #     if json_file:
                #         json_file.close()
                #     self.save_json_path = self.save_json(time_str)
                #     json_file = open(self.save_json_path, 'a', encoding='utf-8')
                #     self.current_time_str = time_str

                # 数据分析
                return_data = self.data_analysis()
                # 添加新数据
                self.add_message(q)
                if last_return_data is None and return_data:
                    last_return_data = return_data
                if return_data and last_return_data:
                    if return_data != last_return_data:
                        # print("数据更新", self.gantry_info["up_gantry_id"], return_data["data"]["time"])
                        # 计算事故
                        data = return_data
                        last_data = last_return_data
                        content, content_info = self.monitor.run(data, last_data)
                        last_return_data = return_data
                        con, density = self.congestion.run(return_data)
                        # 后续均为数据处理操作，主要是拼接字段信息到各自队列以用于上报kafka
                        # 获取新的小客车通行时间duration_info
                        # duration_info = []
                        # for vlp, vlp_data in self.type_pass_time_ture.items():
                        #     duration_info.append(
                        #         {"timestamp": vlp_data["timestamp"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                        #          "vtype": vlp_data["vtype"],
                        #          "vlp": vlp_data["vlp"],
                        #          "carDuration": vlp_data["duration"]})
                        # 计算时间区间内的通过车辆数量和平均速度
                        pass_num = 0
                        for k, v in return_data["data"]["type_speed_dict"].items():
                            pass_num += len(v["speed_list"])
                        if "1" in return_data["data"]["type_speed_dict"]:
                            car_mean_speed = return_data["data"]["type_speed_dict"]["1"]["mean_speed"]
                        else:
                            car_mean_speed = 0
                        data = {"time": self.current_simulated_time, "con": con, "content": content, "num": pass_num,
                                "speed": car_mean_speed, "density": density}
                        # 如果阻断，上报阻断信息到队列
                        # if content != "畅通" or con != "畅通":
                        level.put(data, block=False)
                        logger.info(f"{self.gantry_info['info']} {data}")
                        # 将最新的监测信息等数据放到队列中
                        # 计算事件等级1～5
                        level_dict = {"畅通": 0, "轻度拥堵": 1, "中度拥堵": 2, "严重拥堵": 3, "阻断": 4, "缓行": 5}
                        if content == "畅通" and con == "畅通":
                            event_level = 0
                        elif con != "畅通":
                            event_level = level_dict[con]
                        else:
                            if content == "阻断":
                                event_level = 4
                            else:
                                event_level = 3
                        kafka_data_dict = {}
                        if content_info:
                            kafka_data_dict = {
                                "timestamp": return_data["data"]["time"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                                "sn": self.gantry_info["down_gantry_id"][0],
                                "congestionFlag": con,
                                "eventFlag": content,
                                "abnormalFlag": "正常",
                                "density": density,
                                "flowInfo": {
                                    "upFlow": return_data["data"]["up_flow_num"],
                                    "downFlow": return_data["data"]["down_flow_num"]
                                },
                                # "durationInfo": duration_info,
                                "passRateInfo": content_info["current_pass_rate"],
                                "eventLevel": event_level,
                                "in_num": return_data["data"]["in_num"],
                                "out_num": return_data["data"]["out_num"]
                            }
                            # kafka_data.put(kafka_data_dict, block=False)
                            logger.info(f"{self.gantry_info['info']} {kafka_data_dict}")
                        # 保存过程数据到本地json中
                        if self.SAVE and content_info and kafka_data_dict:
                            orgin_save_data = kafka_data_dict.copy()
                            car_num = 0
                            car_speed = 0
                            car_slow_num = 0
                            if "1" in return_data["data"]["type_speed_dict"]:
                                car_num = return_data["data"]["type_speed_dict"]["1"]["count"]
                                car_speed = return_data["data"]["type_speed_dict"]["1"]["mean_speed"]
                                num = return_data["data"]["type_speed_dict"]["1"]["slow_level_count"]
                                car_slow_num = num[1] + num[2] + num[3]
                            pass_rate_dict = {"pass_num": 0, "all_count": 0}
                            for vtype in return_data["data"]["type_pass_rate_dict"].keys():
                                car_pass_rate = return_data["data"]["type_pass_rate_dict"][vtype]
                                pass_rate_dict["pass_num"] += car_pass_rate["pass"]
                                pass_rate_dict["all_count"] += car_pass_rate["count"]
                            all_pass_rate = int(pass_rate_dict["pass_num"] / pass_rate_dict["all_count"] * 100) if \
                            pass_rate_dict["all_count"] != 0 else 100
                            save_data = {
                                "time": orgin_save_data["timestamp"],
                                "sn": orgin_save_data["sn"],
                                "traffic": orgin_save_data["congestionFlag"],
                                "event": orgin_save_data["eventFlag"],
                                "density": orgin_save_data["density"],
                                "level": orgin_save_data["eventLevel"],
                                "upFlow": orgin_save_data["flowInfo"]["upFlow"],
                                "downFlow": orgin_save_data["flowInfo"]["downFlow"],
                                "passRate": orgin_save_data["passRateInfo"],
                                "flowDiff": content_info["flow_diff"],
                                "frameNum": content_info["one_frame_num"],
                                "carNum": car_num,
                                "carSpeed": car_speed,
                                "carSlowNum": car_slow_num,
                                "durationValue": content_info["duration_value"],
                                "allCount": pass_rate_dict["all_count"],
                                "allPassRate": all_pass_rate,
                                "intervalNum": content_info["interval_diff"],
                                "blockFlag": content_info["block_flag"],
                                "probability": content_info["block_probability"]
                            }
                            logger.info(f"{save_data}")
                            # json_str = json.dumps(save_data, ensure_ascii=False)
                            # json_file.write(json_str + '\n')
            except Exception as e:
                print("error:", e, "process_event", traceback.print_exc())
                pass
